package com.example.exam.service.impl;

import com.example.exam.entity.Choice;
import com.example.exam.entity.ExamPaperAnswer;
import com.example.exam.entity.Question;
import com.example.exam.entity.QuestionAnswer;
import com.example.exam.enums.ResultEnum;
import com.example.exam.exception.ExamPaperException;
import com.example.exam.service.*;
import com.example.exam.util.QuestionType;
import com.example.exam.util.QuestionUtil;
import com.example.exam.vo.QuestionAnswerVO;
import com.example.exam.vo.TeacherCorrectVO;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shishuqian
 * date 2021/5/2
 * time 21:35
 **/
@Service
public class CorrectExamPaperServiceImpl implements CorrectExamPaperService {


    @Autowired
    private ExamPaperAnswerService examPaperAnswerService;

    @Autowired
    private ExamPaperService examPaperService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private ChoiceService choiceService;


    @Override
    public void systemCorrect(Integer examPaperAnswerId) {
        //取出答题卷
        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.findById(examPaperAnswerId);

        //如果试卷不存在
        if (examPaperAnswer == null){
            throw new ExamPaperException(ResultEnum.EXAM_PAPER_NOT_EXIT);
        }
        //考试结束，不能再提交
        //examPaperAnswer.setFinishStatus(true);

        //试卷批改状态，没有简答题就可以完成批改
        examPaperAnswer.setStatus(2);
        Double systemScore = 0.0;  //记录系统判定总得分
        int rightCount = 0;   //记录做对题目数量(只包含系统判定的)
        //操作问题
        for (QuestionAnswer questionAnswer : examPaperAnswer.getQuestionAnswerList()) {
            //单选题
            if (questionAnswer.getQuestionType().equals(QuestionType.DANXUAN)) {
                //未作答
                if (questionAnswer.getUserAnswer() == null || questionAnswer.getUserAnswer().equals("") || questionAnswer.getUserAnswer().equals("-1")) {
                    questionAnswer.setDoRight(false);
                    questionAnswer.setUserScore(0.0);
                } else {  //作答
                    //单选题用户选的答案,在数据库中存储的是某选项的id
                    int id = Integer.parseInt(questionAnswer.getUserAnswer());
                    Choice choice = choiceService.findById(id);
                    if(choice == null){
                        throw new ExamPaperException("测试中选择题的答案是乱填的");
                    }
                    if (choice.getRightAnswer()!=null && choice.getRightAnswer()) {  //作答正确
                        questionAnswer.setDoRight(true);
                        questionAnswer.setUserScore(questionAnswer.getQuestionScore());
                    } else {
                        questionAnswer.setDoRight(false);
                        questionAnswer.setUserScore(0.0);
                    }

                    //取出当前问题的选项，判断此题是否设置了正确答案，如果没设置，默认用户作答正确
                    int questionId = questionAnswer.getQuestionId();
                    List<Choice> choiceList =questionService.findById(questionId).getChoiceList();

                    boolean answerNo = QuestionUtil.setRight(choiceList);
                    if (answerNo){
                        questionAnswer.setDoRight(true);
                        questionAnswer.setUserScore(questionAnswer.getQuestionScore());
                    }
                }

            }

            //多选题
            if (questionAnswer.getQuestionType().equals(QuestionType.DUOXUAN)) {

                if (questionAnswer.getUserAnswer() == null || questionAnswer.getUserAnswer().equals("")|| questionAnswer.getUserAnswer().equals("-1")) {  //未作答或答案为空
                    questionAnswer.setDoRight(false);
                    questionAnswer.setUserScore(0.0);
                } else {  //作答

                    //先假设做对了，如果后面发现做错，再更改分数
                    questionAnswer.setDoRight(true);
                    questionAnswer.setUserScore(questionAnswer.getQuestionScore());

                    String user_answer = questionAnswer.getUserAnswer();
                    String[] answers = user_answer.split("_");
                    boolean flag = true;
                    for (String answer : answers) {
                        int id = Integer.parseInt(answer);
                        Choice choice = choiceService.findById(id);
                        if (choice == null){
                            throw new ExamPaperException("测试中多选题的答案是胡乱填的");
                        }
                        if (choice.getRightAnswer()==null) {  //有一个选项选择错误
                            questionAnswer.setDoRight(false);
                            questionAnswer.setUserScore(0.0);
                            flag = false;
                            break;
                        }
                    }

                    //获取此问题的所有选项
                    List<Choice> choices = questionService.findById(questionAnswer.getQuestionId()).getChoiceList();
                    if (flag) {
                        for (Choice choice : choices) {
                            //该选项是正确的，但是用户没有选，得0分
                            if (choice.getRightAnswer()!=null && choice.getRightAnswer() && !ArrayUtils.contains(answers, choice.getId().toString())) {
                                questionAnswer.setDoRight(false);
                                questionAnswer.setUserScore(0.0);
                                break;
                            }
                        }
                    }

                    boolean noRight = QuestionUtil.setRight(choices);
                    if (noRight){
                        questionAnswer.setDoRight(true);
                        questionAnswer.setUserScore(questionAnswer.getQuestionScore());
                    }

                }

            }

            //判断题，填空题
            if (questionAnswer.getQuestionType().equals(QuestionType.PANDUAN) || questionAnswer.getQuestionType().equals(QuestionType.TIANKONG)) {
                String answer = questionAnswer.getUserAnswer();  //用户填写答案
                if (answer == null || answer.equals("")|| questionAnswer.getUserAnswer().equals("-1")) {  //未作答
                    questionAnswer.setDoRight(false);
                    questionAnswer.setUserScore(0.0);
                } else {  //作答
                    int question_id = questionAnswer.getQuestionId();
                    Question question = questionService.findById(question_id);
                    if (question.getCorrect()==null || answer.equals(question.getCorrect())) {  //答案正确，不设置正确答案默认正确
                        questionAnswer.setDoRight(true);
                        questionAnswer.setUserScore(questionAnswer.getQuestionScore());
                    } else {
                        questionAnswer.setDoRight(false);
                        questionAnswer.setUserScore(0.0);
                    }

                    //没设正确答案的话，coorrect只是由一串____组成
                    String correct = question.getCorrect()+"_";
                    String[] s = correct.split("_");
                    if (s.length==0){
                        questionAnswer.setDoRight(true);
                        questionAnswer.setUserScore(questionAnswer.getQuestionScore());
                    }
                }

            }

            if(questionAnswer.getQuestionType().equals(QuestionType.JIANDA)){
                examPaperAnswer.setStatus(1);
            }

            //填空题


            if (questionAnswer.getUserScore()!=null){
                systemScore += questionAnswer.getUserScore();
            }

            if (questionAnswer.getDoRight()!=null && questionAnswer.getDoRight()){
                rightCount += 1;
            }
        }
        //系统判定得分
        examPaperAnswer.setSystemScore(systemScore);
        //系统判定做对题目数量
        examPaperAnswer.setSystemCorrect(rightCount);
        //当前总分
        examPaperAnswer.setFinalScore(systemScore);
        //如果没有简答题，就不需要老师再批改，直接给最终分
        if (examPaperAnswer.getStatus().equals(2)){
            examPaperAnswer.setTeacherScore(0.0);
            examPaperAnswer.setTeacherCorrect(0);
        }
        //批改完后保存到数据库
        examPaperAnswerService.save(examPaperAnswer);
    }

    @Override
    public TeacherCorrectVO teacherGetQuestion(Integer examPaperAnswerId) {

        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.findById(examPaperAnswerId); //取答题卷

        List<QuestionAnswer> questionAnswers = examPaperAnswer.getQuestionAnswerList();  //取出答题卷的问题

        TeacherCorrectVO teacherCorrectVO = new TeacherCorrectVO();
        List<QuestionAnswerVO> questionAnswerVOList = new ArrayList<>();

        for (QuestionAnswer questionAnswer:questionAnswers){
            //返回简答题
            if(questionAnswer.getQuestionType().equals(QuestionType.JIANDA)){

                //把questionAnswer封装为questionAnswerVO
                QuestionAnswerVO vo = QuestionUtil.questionAnswerTransVO(questionAnswer);
                Question question = questionService.findById(vo.getQuestionId());
                vo.setRowNum(question.getRowNum());
                vo.setContent(question.getContent());
                vo.setCorrect(question.getCorrect());

                questionAnswerVOList.add(vo);
            }
        }
        teacherCorrectVO.setExamPaperAnswerId(examPaperAnswerId);
        teacherCorrectVO.setQuestionAnswerVOList(questionAnswerVOList);
        return teacherCorrectVO;
    }

    @Override
    public void teacherCorrect(TeacherCorrectVO correctVO) {
        int examPaperAnswer_id = correctVO.getExamPaperAnswerId();  //老师批改的答题卷的id
        List<QuestionAnswerVO> questionVO = correctVO.getQuestionAnswerVOList();  //老师批改的问题列表
        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.findById(examPaperAnswer_id); //取出被批改答题卷

        for(QuestionAnswer questionAnswer:examPaperAnswer.getQuestionAnswerList()){
            if(questionAnswer.getQuestionType().equals(QuestionType.JIANDA)){
                //取出对应问题批改信息
                for (QuestionAnswerVO vo:questionVO){
                    if(vo.getId().equals(questionAnswer.getId())){

                        questionAnswer.setDoRight(vo.getDoRight());  //是否正确
                        questionAnswer.setUserScore(vo.getUserScore());  //用户得分
                    }
                }

            }

        }
        //老师评分
        examPaperAnswer.setTeacherScore(correctVO.getTeacherScore());//做对题目总数
        examPaperAnswer.setTeacherCorrect(correctVO.getCorrectNum());
        //试卷总分数
        Double system_score = examPaperAnswer.getSystemScore();
        examPaperAnswer.setFinalScore(system_score+correctVO.getTeacherScore());
        //完成评分
        examPaperAnswer.setStatus(2);
        //保存信息
        examPaperAnswerService.save(examPaperAnswer);
    }


}
